<template>
  <a-modal
    style="width: 50%"
    :title="titleMap[mode]"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :destroyOnClose="true"
    @cancel="handleCancel"
    width="750px"
    :maskClosable="false">
    <div style="margin-top: 12px;">
      <a-form-model ref="ruleAddForm" :model="addForm" :rules="addRules">
        <a-form-model-item label="人员" prop="personId" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-spin :spinning="spinning" tip="加载中...">
            <a-select
              :show-search="false"
              placeholder="请选择人员"
              @popupScroll="popupScroll"
              @change="change"
              optionFilterProp="children"
              v-model="addForm.personId"
              showSearch
              :allow-clear="true"
              @search="onSearch"
              :field-names="{ label: 'name', value: 'partyId' }"
              :option="EmployeesList">
              <a-select-option v-for="(item, index) in EmployeesList" :key="index" :value="item.partyId">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-spin>
          <!-- <a-select :show-search="false" placeholder="请选择人员" optionFilterProp="children"
                        v-model="addForm.personId" showSearch :allow-clear="true"
                        :field-names="{ label: 'name', value: 'partyId' }" :option="EmployeesList">
                        <a-select-option v-for="(item, index) in EmployeesList" :key="item.index" :value="item.partyId">
                            {{ item.name }}
                        </a-select-option>
                    </a-select> -->
        </a-form-model-item>

        <a-form-model-item label="人脸图片" prop="faceUrl" ref="faceUrl" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <div class="clearfix">
            <a-upload
              name="faceImage"
              @change="handleChange"
              :max-count="1"
              list-type="picture-card"
              v-model:file-list="addForm.faceUrl"
              :before-upload="beforeUpload"
              @preview="handlePreview"
              :customRequest="customRequest"
              :remove="handleRemove"
              :limit="1">
              <div v-if="addForm.faceUrl.length < imgNum ? true : false">
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  上传图片
                </div>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="previewCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </div>

        </a-form-model-item>

      </a-form-model>
    </div>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        关闭
      </a-button>
      <a-button type="primary" :visible="visibleBtn" :loading="loadingBtn" @click="handleOk">
        保存
      </a-button>
    </template>
  </a-modal>
</template>
<script>
import { addPersonFaces, detailPersonFaces } from '@/api/clockingIn'
import { getOrg } from '@/api/org'
import { uploadImages } from '@/api/upload'
import { orgEmployees } from '@/api/staff'
import { message, Upload } from 'ant-design-vue'

function getBase64 (file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
    })
}
export default {
    data () {
        return {
            addRules: {
                faceUrl: [
                    { required: true, message: '请上传人脸图片路径!', trigger: 'change' }
                ],
                personId: [
                    { required: true, message: '请选择人员!', trigger: 'change' }

                ]
            },
            addForm: {
                personId: undefined,
                faceUrl: []
            },
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            },
            disable: true,
            visible: false,
            confirmLoading: false,
            loading: false,
            visibleBtn: false,
            loadingBtn: false,
            mode: 'add',
            titleMap: {
                add: '新增',
                edit: '编辑'
            },
            rowData: null,
            EmployeesList: [],

            imgNum: 1, // 设置最多可以上传的图片数量
            previewVisible: false,
            previewImage: '',
            pictureList: [],
            loading: false,

            // 人员
            pageNo: 1,
            max: false,
            spinning: false,
            pageSize: 10,
            searchWorld: '',
            total: 0
        }
    },
    methods: {
        // 加载员工数据
        loadDatas () {
            this.pageNo = 1
            var param = {
                current: this.pageNo,
                pageSize: this.pageSize,
                name: this.searchWorld,
                organizationId: ''
            }
            orgEmployees(param).then((res) => {
                if (res.code == 200) {
                    this.EmployeesList = res.data.datas
                    this.total = res.data.total
                }
            })
        },
        // 滚动条滚动监听方法
        async popupScroll (e) {
            const that = this
            const { target } = e
            const scrollHeight = target.scrollHeight - target.scrollTop // 滑动总高度
            const clientHeight = target.clientHeight // 滑动最低高度
            // 当下拉框滚动条到达底部的时候
            if (!this.max && scrollHeight < clientHeight + 2) {
                this.spinning = true
                // 数据起始条数
                this.pageNo++
                var newList = []
                var param = {
                    current: this.pageNo,
                    pageSize: this.pageSize,
                    name: this.searchWorld,
                    organizationId: ''
                }
                await orgEmployees(param).then((res) => {
                    if (res.code == 200) {
                        newList = res.data.datas
                        that.total = res.data.total
                        if (newList.length == 0) {
                            that.max = true
                        }
                    }
                })
                if (that.total != this.EmployeesList.length) {
                    // 数据追加
                    this.EmployeesList = this.EmployeesList.concat(newList)
                }
                this.spinning = false
            }
        },
        // 下拉框搜索方法
        onSearch (val) {
            if (val.length != 0) {
                this.searchWorld = val
                this.EmployeesList = []
                this.max = false
                this.loadDatas()
            } else {
                this.searchWorld = ''
                this.EmployeesList = []
                this.max = false
                this.loadDatas()
            }
        },
        // 限制上传类型
        async beforeUpload (file) {
            this.pictureList = [...this.pictureList, file]
            const iconSize = file.size / 1024 / 1024 < 3
            const isPNG = file.type === 'image/png' || file.type === 'image/jpeg'
            if (!isPNG || !iconSize) {
                this.pictureList.splice(this.pictureList.indexOf(file), 1)
                message.error(`只能是jpg、png格式且大小不能超过3MB!`)
            }
            return (isPNG && iconSize) || Upload.LIST_IGNORE
        },
        // 上传接口调用
        async customRequest (options) {
            const { onSuccess, onError, file, onProgress } = options
            const formData = new FormData()
            formData.append('filename', file)
            onProgress({ precent: 80 })
            const res = await uploadImages(formData)

            const _this = this
            if (res.code === 200) {
                console.log(res)
                onProgress({ precent: 100 })
                const arr = res.data
                console.log(arr)
                if (Array.isArray(arr) && arr.length > 0) {
                    onSuccess(arr, file)
                    // 上传成功
                    _this.$refs.faceUrl.clearValidate()
                    _this.addForm.faceUrl.push(arr[0].imageUrl)
                    message.success('上传成功')
                }
            } else {
                onError(res.data, file)
                message.error('上传失败')
            }
        },
        // 上传加载状态
        handleChange (info) {
            if (info.file.status === 'uploading') {
                this.loading = true
                return
            }
            if (info.file.status === 'done') {
                this.loading = false
            }
        },
        // 删除
        handleRemove (file) {
            const imageUrl = file.response ? file.response[0].imageUrl : file.imageUrl
            this.addForm.faceUrl.forEach((item, index) => {
                if (item == imageUrl) {
                    this.addForm.faceUrl.splice(index, 1)
                }
            })
            this.addForm.faceUrl = []
        },
        // 关闭预览
        previewCancel () {
            this.previewVisible = false
        },
        // 预览图片获取
        async handlePreview (file) {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj)
            }
            this.previewImage = file.url || file.preview
            this.previewVisible = true
        },
        change (val) {
            this.addForm.personId = val
        },

        // 显示
        open (row) {
            // this.mode = mode;
            console.log(row)
            // getOrg().then(res => {
            //     if (res.code == 200) {
            //         if (res.data.length > 0) {
            //             this.getEmployees(res.data[0].organizationUnitId)
            //         }
            //     }
            // })
            this.addForm.faceUrl = []
            if (this.max) return
            this.loadDatas()
            this.visible = true
            return this
        },

        // 关闭
        handleCancel () {
            this.visible = false
            this.loadingBtn = false
            this.visibleBtn = false
            this.$emit('close')
        },
        // 确认
        handleOk () {
            this.loadingBtn = true
            this.visibleBtn = true
            this.$refs.ruleAddForm.validate(valid => {
                if (valid) {
                    const { personId, faceUrl } = this.addForm
                    const par = {
                        personId: personId == undefined ? '' : personId,
                        faceUrl: faceUrl.length == 0 ? '' : faceUrl[0]
                    }
                    addPersonFaces(par).then(res => {
                        console.log(res)
                        if (res.code === 200) {
                            this.$notification['success']({
                                message: '提示',
                                description: '保存成功！',
                                duration: 8
                            })
                            this.$emit('success')
                            this.visible = false
                        } else {
                            this.$notification['error']({
                                message: '提示',
                                description: res.message,
                                duration: 8
                            })
                        }
                        this.visibleBtn = false
                        this.loadingBtn = false
                    })
                } else {
                    this.loadingBtn = false
                    this.visibleBtn = false
                    return false
                }
            })
        }
    }
}
</script>
<style scoped lang="less" >
.avatar-uploader>.ant-upload {
    width: 128px;
    height: 128px;
}

.img-upload {
    width: auto;
    flex: 1;
}
</style>
